import type { App } from 'vue'

// type Toast = {
//   message: string,
//   type?:'success' | 'error' | 'warning' | 'info',
//   duration?: number,
//   position?: 'top' | 'bottom' | 'left' | 'right' | 'center',
//   closable?: boolean,
//   onClose?: () => void,
// }

class Toast {
  id: string

  constructor(
    public message: string,
    public type?: 'success' | 'error' | 'warning' | 'info',
    public duration?: number,
    public position?: 'top' | 'bottom' | 'left' | 'right' | 'center',
    public closable?: boolean,
    public onClose?: () => void
  ) {
    this.id = crypto.randomUUID()
  }
}

type ToastConfig = Omit<Toast, 'id'>

// export class ToastProvider {
//   toasts = ref<Record<string, Toast>>({})
//   toastList = ref<Toast[]>([])

//   createToast = (config: ToastConfig) => {
//     const toast = new Toast(
//       config.message,
//       config.type ?? 'success',
//       config.duration ?? 3000,
//       config.position ?? 'center',
//       config.closable ?? false,
//       config.onClose
//     )
//     this.toasts.value[toast.id] = toast
//     return toast
//   }

//   addToast = (toast: Toast) => {
//     this.toastList.value.push(toast)
//   }
// }

export const useToast = createGlobalState(() => {
  const toasts = ref<Record<string, Toast>>({})
  const toastList = ref<Toast[]>([])

  const createToast = (config: ToastConfig) => {
    const toast = new Toast(
      config.message,
      config.type ?? 'success',
      config.duration ?? 3000,
      config.position ?? 'center',
      config.closable ?? false,
      config.onClose
    )
    toasts.value[toast.id] = toast
    return toast
  }

  const addToast = (toast: Toast) => {
    toastList.value.push(toast)
    if (toast.duration) {
      setTimeout(() => {
        toastList.value = toastList.value.filter((t) => t.id !== toast.id)
        delete toasts.value[toast.id]
      }, toast.duration)
    }
  }

  return {
    toasts,
    toastList,
    createToast,
    addToast
  }
})

export const createToast = (app: App) => {
  app.config.globalProperties.$toast = (
    message: string,
    type: 'success' | 'error' | 'warning' | 'info' = 'info'
  ) => {}

  app.provide('toast', useToast())
}
